<?php

Yii::import( "application.controllers.FrontendBaseController" );

class PostController extends FrontendBaseController
{

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView( $id )
    {
        $model = $this->loadModel( $id );
        if ( $model->user_id == $this->getUserIdFromSession() )
        {
            $isAuthor = true;
        }
        if ( $isAuthor )
        {
            $nameText = "Моя страница";
            $postText = "Мой блог";
        }
        else
        {
            $user = UserFacade::getUserById( $model->user_id );
            $nameText = $user->name . " " . $user->surname;
            $postText = "Блог";
        }
        $this->breadcrumbs = array( "Главная" => "/",
            $nameText => $this->getUserMainPageUrl( $model->user_id ),
            $postText => "/post/" . $model->user_id,
            $model->title => "",
        );
        $this->render( 'view', array(
            'model' => $model,
            'isAuthor' => $isAuthor,
        ) );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->breadcrumbs = array( "Главная" => "/",
            "Моя страница" => $this->getUserMainPageUrl(),
            "Мои посты" => "/post/",
            "Добавление поста" => "",
        );

        $model = new BlogPost;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if ( isset( $_POST[ 'BlogPost' ] ) )
        {
            $model->attributes = $_POST[ 'BlogPost' ];
            $model->user_id = $this->getUserIdFromSession();

            if ( PostFacade::saveModel( $model ) )
                $this->redirect( array( 'view', 'id' => $model->post_id ) );
        }

        $this->render( 'create', array(
            'model' => $model,
        ) );
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate( $id )
    {
        $model = $this->loadModel( $id );

        $this->breadcrumbs = array( "Главная" => "/",
            "Моя страница" => $this->getUserMainPageUrl(),
            "Мои посты" => "/post/",
            "Редактирование поста &laquo;" . $model->title . "&raquo;" => "",
        );


        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if ( isset( $_POST[ 'BlogPost' ] ) )
        {
            $model->attributes = $_POST[ 'BlogPost' ];
            if ( PostFacade::saveModel( $model ) )
                $this->redirect( array( 'view', 'id' => $model->post_id ) );
        }

        $this->render( 'update', array(
            'model' => $model,
        ) );
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete( $id )
    {
        // we only allow deletion via POST request
        PostFacade::deleteModel( $id );

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if ( !isset( $_GET[ 'ajax' ] ) )
            $this->redirect( isset( $_POST[ 'returnUrl' ] ) ? $_POST[ 'returnUrl' ] : array( 'index' ) );
    }

    /**
     * Lists all models.
     */
    public function actionIndex( $id = null )
    {
        if ( (!isset( $id )) || ($id == $this->getUserIdFromSession()) )
        {
            $isAuthor = true;
        }
        if ( !$isAuthor )
        {
            $user = UserFacade::getUserById( $id );
            $nameText = $user->name . " " . $user->surname;
            $postText = "Блог";
        }
        else
        {
            $nameText = "Моя страница";
            $postText = "Мой блог";
        }
        $this->breadcrumbs = array( "Главная" => "/",
            $nameText => $this->getUserMainPageUrl( $id ),
            $postText => "" );
        if ( !$isAuthor )
        {
            $dataProvider = new CActiveDataProvider( 'BlogPost', array(
                        'criteria' => array( 'condition' => 'user_id=' . $id )
                    ) );
        }
        else
        {
            $dataProvider = new CActiveDataProvider( 'BlogPost', array(
                        'criteria' => array( 'condition' => 'user_id=' . $this->getUserIdFromSession() )
                    ) );
        }

        $this->render( 'index', array(
            'dataProvider' => $dataProvider,
            'isAuthor' => $isAuthor,
                ) );
    }

    public function actionAll()
    {
        $model = new BlogPost;
        $model->unsetAttributes();  // clear any default values

        $this->registerAjaxSearch("post-search", "post-list");
        
        $this->breadcrumbs = array( "Главная" => "/",
            "Все блоги" => "" );

        $title = $_GET['BlogPost']['title'];
        $dataProvider = PostFacade::getDataProviderForSearch($title);
        
        $this->render( 'all', array(
            'dataProvider' => $dataProvider,
            'searchModel' => $model
                ) );
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new BlogPost;
        $model->unsetAttributes();  // clear any default values
        if ( isset( $_GET[ 'BlogPost' ] ) )
            $model->attributes = $_GET[ 'BlogPost' ];

Yii::app()->clientScript->registerScript('search',
    "var ajaxUpdateTimeout;
    var ajaxRequest;
    $('#post-search input').keyup(function(){
        ajaxRequest = $(this).serialize();
        clearTimeout(ajaxUpdateTimeout);
        ajaxUpdateTimeout = setTimeout(function () {
            $.fn.yiiListView.update(
// this is the id of the CListView
                'blog-post-grid',
                {data: ajaxRequest}
            )
        },
// this is the delay
        1000);
    });"
);
        $criteria = new CDbCriteria();
        $title = $_GET['BlogPost']['title'];
        if( strlen( $title ) > 0 )
            $criteria->addSearchCondition( 'title', $title, true, 'OR' );
        $dataProvider = new CActiveDataProvider( 'BlogPost', array( 'criteria' => $criteria, ) );

        $this->render( 'admin', array(
            'model' => $model,
            'dataProvider' => $dataProvider
        ) );
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel( $id )
    {
        return PostFacade::loadModel($id);
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation( $model )
    {
        if ( isset( $_POST[ 'ajax' ] ) && $_POST[ 'ajax' ] === 'blog-post-form' )
        {
            echo CActiveForm::validate( $model );
            Yii::app()->end();
        }
    }

}
